<?php
/**
 * Copyright (c) 2020
 * 摘    要：帮助类traits
 * 作    者：san
 * 修改日期：2020.03.30
 */

namespace App\Library\Traits;

use ErrorException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

trait Helper
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * 表单验证
     *
     * @param $rules
     * @param array $params
     * @throws ErrorException
     * @return bool
     */
    public function validator($rules, $params = [])
    {
        if (!$rules) return true;
        if (!$params) $params = $this->request->all();

        $validator = $this->validationFactory->make($params, $rules);
        if ($validator->fails()) {
            throw new ErrorException($validator->errors()->first());
        }

        return true;
    }

    /**
     * 数据拼装
     *
     * @param $fields
     * @param array $params
     * @return array
     */
    public function combine($fields, $params = [])
    {
        if (!$params) {
            $params = $this->request->all();
        }

        $data = [];
        if (!is_array($fields)) {
            $fields = explode(',', $fields);
        }
        array_map(function ($item) use (&$data, $params) {
            $item         = explode(":", $item);
            $dbKey        = $item[0];
            $postKey      = $item[1] ?? $item[0];
            $data[$dbKey] = $params[$postKey] ?? '';
        }, $fields);

        return $data;
    }
}
